<template>
  <div class="main">
    <view class="user_func">
      <view class="func_setting" >
        <text class="func_desc">我的头像</text>
        <image class="func_icon" :src="src" @click="toPicker"></image>
      </view>

      <view class="func_nickname" @click="toForgetPwd">
        <text class="nickname_desc">我的昵称</text>
        <input class="nickname_input" placeholder="请输入昵称" type="text" v-model="name"/>
      </view>
    </view>

    <text :class="canRegister ? 'btnCanLogin' : 'btnlogin'" :disabled="!canRegister" @click="toCommit">保存</text>
  </div>
</template>

<script>
import store from '@/store/store'
import api from '@/utils/api'
import utils from '@/utils/index'

export default {
  computed: {
    nick_name () {
      return store.state.nick_name
    },
    avatar () {
      return store.state.avatar
    },
    cookie () {
      return store.state.cookie
    },
    url () {
      return store.state.url
    }
  },
  data () {
    return {
      canRegister: true,
      src: 'http://fanglilai-pic.oss-cn-shenzhen.aliyuncs.com/mw690/20180619/2018061905173945299.jpg',
      name: ''
    }
  },
  methods: {
    toPicker () {
      var _this = this
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths

          wx.uploadFile({
            url: _this.url + 'apii/user/opupload',
            filePath: tempFilePaths[0],
            name: 'img[0]',
            formData: {
              'name': 'img[0]'
            },
            header: {
              'Content-Type': 'multipart/form-data',
              'Cookie': _this.cookie
            },
            success: function (res) {
              console.log(res)
              var data = JSON.parse(res.data)
              _this.src = data.data[0]
            },
            fail: function (res) {
            }
          })
        }
      })
    },
    toCommit () {
      var param = {}
      param['nick_name'] = this.name
      param['avatar'] = utils.find(this.src, '/', 2)
      const opuserinfosave = api.opuserinfosave(param)
      opuserinfosave.then(d => {
        if (d.code === 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          })
          setTimeout(function () {
            wx.navigateBack()
          }, 1000)
        }
      })
      .catch((e) => {
        console.log(e)
      })
    }
  },
  onLoad () {
    console.log(this.cookie)
    if (this.avatar !== '') {
      this.src = this.avatar
    }
    this.name = this.nick_name
  }
}
</script>

<style>
@import './userinfo_edit.css';
</style>
